package com.hdoit.apollo.web.purchase.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.common.enums.billing.PayState;
import com.hdoit.apollo.logical.common.enums.purchase.AllocationState;
import com.hdoit.apollo.logical.common.enums.purchase.PurchaseState;
import com.hdoit.apollo.logical.common.enums.stock.InStockState;
import com.hdoit.apollo.logical.common.enums.stock.InStockType;
import com.hdoit.apollo.logical.inStock.model.InStock;
import com.hdoit.apollo.logical.inStock.service.IInStockService;
import com.hdoit.apollo.logical.purchase.model.Purchase;
import com.hdoit.apollo.logical.purchase.model.PurchaseCollocation;
import com.hdoit.apollo.logical.purchase.service.IPurchaseCollocationService;
import com.hdoit.apollo.logical.purchase.service.IPurchaseService;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.model.SupplyCargo;
import com.hdoit.apollo.logical.shop.service.ISupplyCargoService;
import com.hdoit.apollo.logical.viewmodel.purchase.PurchaseSearch;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;

/**
 * @author      humaoshu
 * @email       
 * @createtime  2018年05月23日 09:54:04
 * @comment
 */
@Controller
@RequestMapping(value = "/purchase/purchase/")
public class PurchaseController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/purchase/purchase/";
    }
    
    @Autowired
    private IInStockService inStockService;
    
    @Autowired
    private IPurchaseService purchaseService;
   
    @Autowired
    private IPurchaseCollocationService purchaseCollocationService;
    
    @Autowired
    private ISupplyCargoService supplyCargoService;

    private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="purchaseDetailed";
    private final String addDetailed="addDetailed";
    private final String editDetailed="editDetailed";
    private final String purchaseClose="purchaseClose";
    
    private final String otherViewName="otherDetailed";
    private final String purposeViewName="purposeDetailed";
    private final String saveViewName="save";
    
    private final String saveInStockViewName="saveInStock";
    private final String saveOutStockViewName="saveOutStock";

    
    
    private final String deleteViewName = "delete";
    private final String supplierSelectViewName="supplierSelect";
    
    private final String purchaseIndexViewName = "purchaseIn/index";
    private final String purchaseInViewName = "purchaseIn";
    
    private final String printViewName = "purchaseDetailPrint";
    
    private final String inStockPrintViewName = "inStockDetailPrint";
    private final String returnCargoViewName = "returnCargoDetailed";
    
    private final String seePurposeViewName = "seePurposes";
    private final String seeInStockViewName = "seeInStock";
    private final String selInStock = "selInStock";
    
    @RequestMapping(value = returnCargoViewName, method = { RequestMethod.GET})
    public String returnCargo(Model model,String key){
        Purchase purchase=new Purchase();
        InStock inStock=new InStock();
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModelByKey(key);
            
        }
        model.addAttribute("purchase", purchase);
        model.addAttribute("inStock", inStock);
        return view(returnCargoViewName);
    }
    
    @RequestMapping(value = purchaseInViewName, method = { RequestMethod.GET})
    public String purIn(Model model,String purchaseId){
        Purchase purchase=new Purchase();
        InStock inStock=new InStock();
        List<InStock> inStocks=new ArrayList<InStock>();
        if(!StringUtils.isEmpty(purchaseId)){
            purchase=purchaseService.queryModelByKey(purchaseId);
            
            inStocks=inStockService.queryInStockHistoryListByKey(purchaseId);
            
        }
        model.addAttribute("purchase", purchase);
        model.addAttribute("inStock", inStock);
        model.addAttribute("inStocks", inStocks);
        return view(purchaseInViewName);
    }
    
    @RequestMapping(value = purchaseIndexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String purchaseIndex(Model model,PagerModel pagerModel,PurchaseSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(purchaseService.queryCountMP(search));
        List<Purchase> purchases= purchaseService.queryListMP(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("purchases", purchases);
        model.addAttribute("purchaseSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(purchaseIndexViewName);
    }

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,PurchaseSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(purchaseService.queryCountMP(search));
        List<Purchase> purchases= purchaseService.queryListMP(search,pagerModel);
       

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("purchases", purchases);
        model.addAttribute("purchaseSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }
    
    @RequestMapping(value = otherViewName, method = { RequestMethod.GET})
    public String other(Model model,String key){
        Purchase purchase=new Purchase();
        List<PurchaseCollocation> purchaseCollocations=null;
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModelByKey(key);
            purchaseCollocations=purchaseCollocationService.queryListByPurchaseId(key);
        }
        model.addAttribute("purchase", purchase);
        model.addAttribute("purchaseCollocations", purchaseCollocations);
        return view(otherViewName);
    }
    
    @RequestMapping(value = seeInStockViewName, method = { RequestMethod.GET})
    public String seeInStock(Model model,String key){
    	 List<InStock> inStocks=new ArrayList<InStock>();
        
        if(!StringUtils.isEmpty(key)){
        	 inStocks=inStockService.queryInStockHistoryListByKey(key);
            
        }
        model.addAttribute("inStocks", inStocks);
        return view(seeInStockViewName);
    }
    
    @RequestMapping(value = selInStock, method = { RequestMethod.GET})
    public String selInStock(Model model,String key){
    	 InStock inStock=new InStock();
        
        if(!StringUtils.isEmpty(key)){
        	inStock=inStockService.queryModelBySee(key);
            
        }
        model.addAttribute("inStock", inStock);
        return view(selInStock);
    }
    
    
    @RequestMapping(value = seePurposeViewName, method = { RequestMethod.GET})
    public String seePurpose(Model model,String key){
        Purchase purchase=new Purchase();
        
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModelByKey(key);
            
        }
        model.addAttribute("purchase", purchase);
        return view(seePurposeViewName);
    }
    
    
    @RequestMapping(value = purposeViewName, method = { RequestMethod.GET})
    public String purpose(Model model,String key){
        Purchase purchase=new Purchase();
        
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModelByKey(key);
            
        }
        model.addAttribute("purchase", purchase);
        return view(purposeViewName);
    }

    
    
    
    @RequestMapping(value = addDetailed, method = { RequestMethod.GET})
    public String purchaseDetailed(Model model,String key){
        Purchase purchase=new Purchase();
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModel(key);
        }
        String timestamp = DateUtils.convertDate2String("yyyyMMddHHmmss", DateUtils.getCurrent());
        purchase.setPurchaseNo("CG-"+timestamp);
        model.addAttribute("purchase", purchase);
        return view(addDetailed);
    }
    
    @RequestMapping(value = editDetailed, method = { RequestMethod.GET})
    public String editDetailed(Model model,String key){
        Purchase purchase=new Purchase();
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModelByKey(key);
        }
        model.addAttribute("purchase", purchase);
        return view(editDetailed);
    }
    
    @RequestMapping(value = purchaseClose, method = { RequestMethod.POST},produces = "text/html;charset=UTF-8")
    public @ResponseBody String purchaseClose(Model model,String key){
    	Purchase purchase=new Purchase();
        if(!StringUtils.isEmpty(key)){
            purchase=purchaseService.queryModelByKey(key);
            purchase.setPurchaseState(PurchaseState.close);
        }
    	if(!purchaseService.closePurchase(purchase,getLoginModel().getLoginId(),getLoginModel().getLoginName())){
    		return new JsonActionResult(ManageContainer.ERROR).toJson();
    	}
		
		return new JsonActionResult(ManageContainer.SUCCESS).toJson();
    }
    
    
    @RequestMapping(value = saveOutStockViewName, method = { RequestMethod.POST})
    public String saveOutStock(Model model,InStock inStock,String ids){
    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    	String [] numMark=inStock.getInStockNums().split(",");
     	String [] prices=inStock.getInStockPrices().split(",");
     	
        if(StringUtils.isEmpty(inStock.getInStockId())){
        	
        	Double num=0.0;
        	Double price=0.0;
        	
        	for (int i = 0; i < numMark.length; i++) {
				
        		
        		Double numberMark=Double.parseDouble(numMark[i]);
				Double priceMark=Double.parseDouble(prices[i])*numberMark;
				
				price=priceMark+price;
				num=numberMark+num;
			}
        	inStock.setInStockNum(num);
        	inStock.setReturnMoney(price);
        	inStock.setInStockId(CommonUtils.getKeyId());
        	inStock.setCreateDate(DateUtils.getCurrent());
        	inStock.setDeleteMark(YesOrNoInteger.no);
        	inStock.setCreateUserId(getLoginModel().getLoginId());
        	inStock.setCreateUserName(getLoginModel().getLoginName());
        	inStock.setShopId(shop.getShopId());
        	inStock.setType(InStockType.outWarehouse);
        	inStock.setInStockState(InStockState.finish);
        	inStock.setModelStatus(ModelStatus.add);
        }else{
        	inStock.setModifyDate(DateUtils.getCurrent());
        	inStock.setModifyUserId(getLoginModel().getLoginId());
        	inStock.setModifyUserName(getLoginModel().getLoginName());
        	inStock.setModelStatus(ModelStatus.update);
        }
        

        ActionResult actionResult;
        if(inStockService.applyInStockForPC(inStock,ids)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("inStock", inStock);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }
    
    
    @RequestMapping(value = saveInStockViewName, method = { RequestMethod.POST})
    public String saveInStock(Model model,InStock inStock,String ids){
    	 Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    	 String [] numMark=inStock.getInStockNums().split(",");
        if(StringUtils.isEmpty(inStock.getInStockId())){
        	Double num=0.0;
        	
        	for (int i = 0; i < numMark.length; i++) {
				
				Double numberMark=Double.parseDouble(numMark[i]);
				
				num=numberMark+num;
			}
        	inStock.setInStockNum(num);
            inStock.setInStockId(CommonUtils.getKeyId());
            inStock.setCreateDate(DateUtils.getCurrent());
            inStock.setDeleteMark(YesOrNoInteger.no);
            inStock.setCreateUserId(getLoginModel().getLoginId());
            inStock.setCreateUserName(getLoginModel().getLoginName());
            inStock.setType(InStockType.inWarehouse);
            inStock.setShopId(shop.getShopId());
            inStock.setModelStatus(ModelStatus.add);
            
        }else{
            inStock.setModifyDate(DateUtils.getCurrent());
            inStock.setModifyUserId(getLoginModel().getLoginId());
            inStock.setModifyUserName(getLoginModel().getLoginName());
            inStock.setModelStatus(ModelStatus.update);
        }
        

        ActionResult actionResult;
        if(inStockService.applyInStockForPC(inStock,ids)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("inStock", inStock);
       
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(purchaseInViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Purchase purchase){
    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
        if(StringUtils.isEmpty(purchase.getPurchaseId())){
        	
        	Double price=0.0;
        	Double num=0.0;
        	
			String[] purchaseNums=purchase.getPurchaseNums().split(",");
			String[] purchasePrices=purchase.getPurchasePrices().split(",");
			for (int i = 0; i < purchaseNums.length; i++) {
				
				Double numberMark=Double.parseDouble(purchaseNums[i]);
				
				num=numberMark+num;
	
				Double mark=Double.parseDouble(purchasePrices[i]);
				price=mark*numberMark+price;
				
			}
            purchase.setPurchaseId(CommonUtils.getKeyId());
            purchase.setCreateDate(DateUtils.getCurrent());
            purchase.setDeleteMark(YesOrNoInteger.no);
            purchase.setCreateUserId(getLoginModel().getLoginId());
            purchase.setCreateUserName(getLoginModel().getLoginName());
            purchase.setShopId(shop.getShopId());
            purchase.setModelStatus(ModelStatus.add);
            purchase.setAllocationState(AllocationState.stayAllocation);
            purchase.setPurchaseNum(num);
            purchase.setPayState(PayState.unpaid);
            if (StringUtils.isEmpty(purchase.getOtherMoney())) {
				purchase.setOtherMoney(0.0);
			}
            purchase.setPurchaseState(PurchaseState.stayIn);
            purchase.setPurchaseInNum(0.0);

            purchase.setHavePayMoney(0.0);


        }else{
            purchase.setModifyDate(DateUtils.getCurrent());
            purchase.setModifyUserId(getLoginModel().getLoginId());
            purchase.setModifyUserName(getLoginModel().getLoginName());
            purchase.setModelStatus(ModelStatus.update);
        }
        
        
        

        ActionResult actionResult;
        if(purchaseService.applyPurchaseForPC(purchase)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("purchase", purchase);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(addDetailed);
    }
    
    @RequestMapping(value = supplierSelectViewName, method = { RequestMethod.GET }, produces = "text/html;charset=UTF-8")
   	public @ResponseBody String supplierSelect(String supplierId) {
    	
    	 List<SupplyCargo> supplyCargos=supplyCargoService.queryListBySupplierId(supplierId);
   		
   		return JsonUtils.writeValueAsString(supplyCargos);
   	}
    
    
    @RequestMapping(value = printViewName, method = { RequestMethod.GET,RequestMethod.POST })
	public String print(Model model, String key) {
		Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
		Purchase purchase = new Purchase();

		if (!StringUtils.isEmpty(key)) {
			purchase = purchaseService.queryModelByKey(key);	
		}
		
		if (purchase!=null) {			
			model.addAttribute("purchase", purchase);
		}
		model.addAttribute("shop", shop);
		return view(printViewName);
	}
    
    
    @RequestMapping(value = inStockPrintViewName, method = { RequestMethod.GET,RequestMethod.POST })
	public String inStockPrint(Model model, String key) {
		Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
		//Purchase purchase = new Purchase();
		InStock inStock=new InStock();

		if (!StringUtils.isEmpty(key)) {
			inStock = inStockService.queryModelBySee(key);	
		}
		
		if (inStock!=null) {			
			model.addAttribute("inStock", inStock);
		}
		model.addAttribute("shop", shop);
		return view(inStockPrintViewName);
	}
    

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(purchaseService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
}
